# -*- coding: utf-8 -*-
from django.shortcuts import render, redirect
from django.http.response import JsonResponse
from django import forms
from django.views import View
from rbac import models
from utils.pagination import Pagination


class RoleForm(forms.ModelForm):
	def __init__(self, *args, **kwargs):
		super().__init__(*args, **kwargs)
		for field in self.fields.values():
			field.widget.attrs = {'class': 'form-control'}

	class Meta:
		model = models.Role
		fields = '__all__'

		error_messages = {
			'name': {'required': '必填项'},
		}

class Role_list(View):
	'''角色列表'''

	def get(self, request):
		role_all = models.Role.objects.all()
		page_obj = Pagination(len(role_all), request.GET.get('page'))
		page_html = page_obj.page_html
		role_list = role_all[page_obj.start:page_obj.end]
		return render(request, 'role/role_list.html', locals())


class Role_lookPermission(View):
	'''查看权限列表'''

	def get(self, request, pk):
		permission_all = models.Role.objects.filter(pk=pk).first().permissions.all()
		page_obj = Pagination(len(permission_all), request.GET.get('page'))
		page_html = page_obj.page_html
		permission_list = permission_all[page_obj.start:page_obj.end]
		return render(request, 'permission/permission_list.html', locals())


class Role_add(View):
	'''添加角色'''

	def get(self, request):
		role_form = RoleForm()
		return render(request, 'role/role_add.html', locals())

	def post(self, request):
		role_form = RoleForm(request.POST)
		if role_form.is_valid():
			role_form.save()
			return redirect('role_list')
		return render(request, 'role/role_add.html', locals())


class Role_edit(View):
	'''编辑角色'''

	def get(self, request, pk):
		role_obj = models.Role.objects.filter(pk=pk).first()
		role_form = RoleForm(instance=role_obj)
		return render(request, 'role/role_edit.html', locals())

	def post(self, request, pk):
		role_obj = models.Role.objects.filter(pk=pk).first()
		role_form = RoleForm(request.POST, instance=role_obj)
		if role_form.is_valid():
			role_form.save()
			return redirect('role_list')
		return render(request, 'role/role_edit.html', locals())


class Role_del(View):
	'''删除角色'''

	def post(self, request, pk):
		ret = {'status': 0, 'msg': '删除成功'}
		if not models.Role.objects.filter(pk=pk).delete():
			ret['msg'] = '删除失败'
		return JsonResponse(ret)